<template>
	<div class="layout-padding">
		<div class="layout-padding-auto layout-padding-view">
			<el-row v-show="showSearch">
				<el-form ref="queryRef" :inline="true" :model="state.queryForm" @keyup.enter="getDataList">
					<el-form-item :label="$t('common.search')" prop="search">
						<el-input
							v-model="state.queryForm.search"
							:placeholder="$t('Order.input') + $t('Order.OrderId') + '/' + $t('Order.userNickname') + '/' + $t('Order.shopName')"
							clearable
							style="width: 350px"
							@clear="getDataList"
						/>
					</el-form-item>

					<el-form-item :label="$t('Order.type')" prop="type">
						<el-select v-model="state.queryForm.type" :placeholder="$t('Order.inputTypeTip')" clearable filterable @clear="getDataList">
							<el-option v-for="(item, index) in biz_order_type" :key="index" :label="item.label" :value="item.value"></el-option>
						</el-select>
					</el-form-item>
					<!-- <el-form-item :label="$t('Order.state')" prop="state">
            <el-select v-model="state.queryForm.state" :placeholder="$t('Order.inputStateTip')" clearable filterable @clear="getDataList" >
              <el-option :value="item.value" :label="item.label" v-for="(item, index) in biz_order_state" :key="index"></el-option>
            </el-select>
      </el-form-item> -->

					<!-- <el-form-item prop="uid" :label="$t('Order.uid')">
            <el-input v-model="state.queryForm.uid" :placeholder="$t('Order.inputUidTip')" clearable
              @clear="getDataList" />
          </el-form-item>
          <el-form-item prop="userNickname" :label="$t('Order.userNickname')">
            <el-input v-model="state.queryForm.userNickname" :placeholder="$t('Order.inputUserNicknameTip')"
              clearable @clear="getDataList" />
          </el-form-item>
          <el-form-item prop="shopName" :label="$t('Order.shopName')">
            <el-input v-model="state.queryForm.shopName" :placeholder="$t('Order.inputShopNameTip')" clearable
              @clear="getDataList" />
          </el-form-item> -->
					<el-form-item :label="$t('Order.payMethod')" prop="payMethod">
						<el-select v-model="state.queryForm.payMethod" clearable filterable>
							<el-option v-for="(item, index) in biz_order_pay_method" :key="index" :label="item.label" :value="item.value"></el-option>
						</el-select>

						<!-- <el-input v-model="state.queryForm.payMethod" :placeholder="$t('Order.inputPayMethodTip')" clearable
              @clear="getDataList" /> -->
					</el-form-item>
					<el-form-item :label="$t('Order.source')" prop="source">
						<el-select v-model="state.queryForm.source" :placeholder="$t('Order.inputSourceTip')" clearable filterable @clear="getDataList">
							<el-option v-for="(item, index) in biz_source" :key="index" :label="item.label" :value="item.value"></el-option>
						</el-select>
					</el-form-item>

					<el-form-item :label="$t('common.createTime')" prop="isHot">
						<el-date-picker
							v-model="state.queryForm.rangeTime"
							:end-placeholder="$t('common.endTime')"
							:shortcuts="rangeTimeShortcuts"
							:start-placeholder="$t('common.startTime')"
							:value-format="$dateTimePattern"
							range-separator="~"
							type="daterange"
							unlink-panels
							@change="getDataList"
						>
						</el-date-picker>
					</el-form-item>

					<el-form-item>
						<el-button icon="search" type="primary" @click="getDataList">
							{{ $t('common.queryBtn') }}
						</el-button>
						<el-button icon="Refresh" @click="resetQuery">{{ $t('common.resetBtn') }}</el-button>
					</el-form-item>
				</el-form>
			</el-row>
			<el-row>
				<div class="mb8" style="width: 100%">
					<el-button v-auth="'bizs_Order_add'" class="ml10" icon="folder-add" type="primary" @click="formDialogRef.openDialog()">
						{{ $t('common.addBtn') }}
					</el-button>
					<el-button v-auth="'bizs_Order_del'" :disabled="multiple" icon="Delete" plain type="primary" @click="handleDelete(selectObjs)">
						{{ $t('common.delBtn') }}
					</el-button>
					<right-toolbar
						v-model:showSearch="showSearch"
						:export="'bizs_Order_export'"
						class="ml10 mr20"
						style="float: right"
						@exportExcel="exportExcel"
						@queryTable="getDataList"
					></right-toolbar>
				</div>
			</el-row>

			<el-tabs v-model="activeStatus" class="demo-tabs" type="card" @tab-change="handleChange">
				<el-tab-pane :label="$t('Order.all	')" name=""></el-tab-pane>
				<el-tab-pane
					v-for="(item, index) in biz_order_state.sort((a: any, b: any) => Number(a.value) - Number(b.value))"
					:key="index"
					:label="item.label"
					:name="item.value"
				></el-tab-pane>
			</el-tabs>

			<el-table
				v-loading="state.loading"
				:cell-style="tableStyle.cellStyle"
				:data="state.dataList"
				:header-cell-style="tableStyle.headerCellStyle"
				border
				@selection-change="selectionChangHandle"
				@sort-change="sortChangeHandle"
			>
				<el-table-column type="expand">
					<template #default="{ row }">
						<el-table :cell-style="tableStyle.cellStyle" :data="row.orderItemList" :header-cell-style="tableStyle.headerCellStyle">
							<el-table-column :label="$t('Order.productInfo')" prop="prod">
								<template #default="props">
									<div class="prod-img-box">
										<img :src="$getFileUri(props.row.pic)" class="br-12" />
										<!-- <img src="/@/assets/lockScreen.png"> -->
										<div>
											<span>{{ $t('Order.prodName') }}:{{ props.row.prodName }}</span>
											<div>{{ props.row.properties }}</div>
										</div>
									</div>
								</template>
							</el-table-column>
							<!-- <el-table-column prop="prod" :label="$t('Order.prodName')"> </el-table-column> -->
							<el-table-column :label="$t('Order.prodId')" prop="prodId"></el-table-column>
							<el-table-column :label="$t('Order.amount')" prop="amount"></el-table-column>
							<el-table-column :label="$t('Order.num')" prop="num"></el-table-column>
						</el-table>
					</template>
				</el-table-column>

				<el-table-column :label="$t('Order.OrderId')" header-align="center" min-width="200" prop="id" show-overflow-tooltip>
					<template #default="scope">
						{{ scope.row.id }}
						<SvgIcon class="icon_copy" name="ele-CopyDocument" @click="copyText(scope.row.id)" />
					</template>
				</el-table-column>

				<!--<el-table-column type="index" label="#" width="40" />-->
				<el-table-column :label="$t('Order.type')" prop="type" show-overflow-tooltip>
					<template #default="scope">
						<dict-tag :options="biz_order_type" :value="scope.row.type"></dict-tag>
					</template>
				</el-table-column>
				<el-table-column :label="$t('Order.state')" prop="state" show-overflow-tooltip>
					<template #default="scope">
						<dict-tag :options="biz_order_state" :value="scope.row.state"></dict-tag>
					</template>
				</el-table-column>
				<!-- <el-table-column prop="uid" :label="$t('Order.uid')" show-overflow-tooltip /> -->
				<el-table-column :label="$t('Order.userInfo')" prop="userNickname" show-overflow-tooltip width="130">
					<template #default="{ row }">
						<card-info-col :icon="row.userAvatar" :name="row.userNickname" />
					</template>

					<!-- <template #default="{ row }">
            <div>
              {{ row.userNickname }}
            </div>
            <div>({{ row.orderAddressCode }}){{ row.orderAddressPhone }}</div>
          </template> -->
				</el-table-column>
				<el-table-column :label="$t('Order.shopInfo')" prop="shopName" show-overflow-tooltip>
					<template #default="{ row }">
						<card-info-col :icon="row.shopAvatar" :name="row.shopName" />
					</template>
				</el-table-column>
				<el-table-column :label="$t('Order.orderAmount')" prop="orderAmount" show-overflow-tooltip>
					<template #default="{ row }">
						{{ $amountFormat(row.orderAmount) }}
					</template>
				</el-table-column>
				<el-table-column :label="$t('Order.actualAmount')" prop="actualAmount" show-overflow-tooltip>
					<template #default="{ row }">
						{{ $amountFormat(row.actualAmount) }}
					</template>
				</el-table-column>
				<el-table-column :label="$t('Order.reduceAmount')" prop="reduceAmount" show-overflow-tooltip>
					<template #default="{ row }">
						{{ $amountFormat(row.reduceAmount) }}
					</template>
				</el-table-column>
				<el-table-column :label="$t('Order.payMethod')" prop="payMethod" show-overflow-tooltip>
					<template #default="scope">
						<dict-tag :options="biz_order_pay_method" :value="scope.row.payMethod"></dict-tag>
					</template>
				</el-table-column>
				<el-table-column :label="$t('Order.time')" min-width="180" prop="payTime" show-overflow-tooltip>
					<template #default="{ row }">
						<div v-if="row.createTime">{{ $t('Order.createTime') }}：{{ row.createTime }}</div>
						<div v-if="row.payTime">{{ $t('Order.payTime') }}：{{ row.payTime }}</div>
						<div v-if="row.deliveryTime">{{ $t('Order.deliveryTime') }}：{{ row.deliveryTime }}</div>
						<div v-if="row.receivingTime">{{ $t('Order.receivingTime') }}：{{ row.receivingTime }}</div>
						<div v-if="row.completeTime">{{ $t('Order.completeTime') }}：{{ row.completeTime }}</div>
						<div v-if="row.cancelTime">{{ $t('Order.cancelTime') }}：{{ row.cancelTime }}</div>
					</template>
				</el-table-column>
				<!-- <el-table-column prop="deliveryTime" :label="$t('Order.deliveryTime')" show-overflow-tooltip /> -->
				<el-table-column :label="$t('Order.source')" prop="source" show-overflow-tooltip>
					<template #default="scope">
						<dict-tag :options="biz_source" :value="scope.row.source"></dict-tag>
					</template>
				</el-table-column>
				<el-table-column :label="$t('Order.remark')" prop="remark" show-overflow-tooltip />
				<!-- <el-table-column prop="createTime" :label="$t('Order.createTime')" show-overflow-tooltip /> -->
				<el-table-column :label="$t('common.action')" min-width="150">
					<template #default="scope">
						<el-button v-if="scope.row.state == 2" icon="edit-pen" text type="primary" @click="deliveryFn(scope.row.id)"
							>{{ $t('Order.delivery') }}
						</el-button>
						<el-button v-if="scope.row.state !== 6" icon="CircleClose" text type="primary" @click="closeOrderFn(scope.row.id)"
							>{{ $t('Order.closeOrder') }}
						</el-button>
						<el-button v-if="scope.row.state == 1" icon="edit-pen" text type="primary" @click="changePriceFn(scope.row.id, scope.row.orderAmount)"
							>{{ $t('Order.modifyThePrice') }}
						</el-button>

						<el-button v-auth="'bizs_Order_edit'" icon="View" text type="primary" @click="formDialogRef.openDialog(scope.row.id)"
							>{{ $t('Order.view') }}
						</el-button>
						<el-button v-auth="'bizs_Order_del'" icon="delete" text type="primary" @click="handleDelete([scope.row.id])"
							>{{ $t('common.delBtn') }}
						</el-button>
					</template>
				</el-table-column>
			</el-table>
			<pagination v-bind="state.pagination" @size-change="sizeChangeHandle" @current-change="currentChangeHandle" />
		</div>

		<!-- 编辑、新增  -->
		<form-dialog ref="formDialogRef" :tableStyle="tableStyle" @refresh="getDataList(false)" />
		<!-- 修改价格 -->
		<ChangePrice ref="ChangePriceREF" @refresh="getDataList(false)"></ChangePrice>
		<!-- 发货表单 -->
		<Delivery ref="deliverRef" :getDataList="getDataList" />
	</div>
</template>

<script lang="ts" name="systemOrder" setup>
import { BasicTableProps, useTable } from '/@/hooks/table';
import { useMessage, useMessageBox } from '/@/hooks/message';
import { closeOrderAPI, delObjs, getPage } from '/@/api/bizs/Order';
import commonFunction from '/@/utils/commonFunction';
import CardInfoCol from '/@/components/biz/card-info-col.vue';
import Delivery from './components/deliver.vue';
// 定义i18n
import { useI18n } from 'vue-i18n';
// 定义查询字典
import { useDict } from '/@/hooks/dict';
import {rangeTimeShortcuts} from "/@/utils/date";

const { t } = useI18n();
const route = useRoute();
const deliverRef = ref();

// 引入组件
const FormDialog = defineAsyncComponent(() => import('./form.vue'));
const ChangePrice = defineAsyncComponent(() => import('./components/changePrice/index.vue'));

const { copyText } = commonFunction();

const { biz_order_type, biz_order_state, biz_source, biz_order_pay_method } = useDict(
	'biz_order_type',
	'biz_order_state',
	'biz_source',
	'biz_order_pay_method'
);
// 定义变量内容
const formDialogRef = ref();
// 搜索变量
const queryRef = ref();
const showSearch = ref(true);
// 多选变量
const selectObjs = ref([]) as any;
const multiple = ref(true);

// 组件ref
const ChangePriceREF = ref();

const state: BasicTableProps = reactive<BasicTableProps>({
	queryForm: {},
	pageList: getPage,
});

// const tabList = ref<string[]>([
//   "全部订单",
//   "最近的订单",
//   "等待买家付款",
//   "等待发货",
//   "已发货",
//   "售后中",
//   "成功的订单",
//   "关闭的订单",
//   "历史订单"
// ])
const activeStatus = ref('');

//  table hook
const { getDataList, currentChangeHandle, sizeChangeHandle, sortChangeHandle, downBlobFile, tableStyle } = useTable(state);

/**
 * 关闭订单
 *
 */
const closeOrderFn = async (id: string | number) => {
	try {
		await useMessageBox().confirm(t('Order.closeConfirmText'));
	} catch {
		return;
	}
	try {
		await closeOrderAPI(id);
		getDataList();
		useMessage().success(t('Order.OrderCloseSuccess'));
	} catch (err: any) {
		useMessage().error(err.msg);
	}
};

// 发货
const deliveryFn = async (id: string) => {
	deliverRef.value.visible = true;
	deliverRef.value.orderId = id;
};

// 修改价格
const changePriceFn = (id: string, orderAmount: string) => {
	// console.log(id)
	ChangePriceREF.value.visible = true;
	ChangePriceREF.value.prodId = id;
	ChangePriceREF.value.orderAmount = orderAmount;
};

// 状态切换
const handleChange = (e: number) => {
	if (e) {
		state.queryForm.state = e;
	} else {
		delete state.queryForm.state;
	}
	getDataList();
};

// 清空搜索条件
const resetQuery = () => {
	// 清空搜索条件
	queryRef.value?.resetFields();
	// 清空多选
	selectObjs.value = [];
	state.queryForm.search = '';
	getDataList();
};

// 导出excel
const exportExcel = () => {
	downBlobFile('/bizs/order/export', Object.assign(state.queryForm, { ids: selectObjs }), 'Order.xlsx');
};

// 多选事件
const selectionChangHandle = (objs: { id: string }[]) => {
	selectObjs.value = objs.map(({ id }) => id);
	multiple.value = !objs.length;
};

// 删除操作
const handleDelete = async (ids: string[]) => {
	try {
		await useMessageBox().confirm(t('common.delConfirmText'));
	} catch {
		return;
	}

	try {
		await delObjs(ids);
		getDataList();
		useMessage().success(t('common.delSuccessText'));
	} catch (err: any) {
		useMessage().error(err.msg);
	}
};

if (route.query.orderId) {
	state.queryForm.search = route.query.orderId;
	getDataList();
}
</script>

<style lang="scss" scoped>
.prod-img-box {
	display: flex;
	gap: 12px;

	img {
		width: 100px;
	}
}
</style>
